import {
  commonManageSearchParams,
  getCompanyID,
  getLoadMapList,
  getPosIDs,
  getSelectDataMapList,
  getTenantID,
  getUserDepID,
  getUserID,
  requestFunComponFiex,
  requestFunHtml,
} from '@/utils';
import { useRequest } from 'umi';
import { ILoadMapTypeAll, ISearchTranslateAll } from '@/common';
import { adminAreadDataGet, loadMdicMap } from '@/services/BaseLayout';
import { useCallback, useMemo, useState } from 'react';
import { AssetacquisitionManageAPI } from '../common/type';
import { ManageSearchColumns } from '../mconfig';
import { disposeArea } from '../common';
import { getRequestIp } from '../../Acommon';
import { AssetacquisitionTabSwitch, DifferTabSwitch, DtailedTabSwitch, ExportSwitch, inventoryerSwitch } from '../mconfig/ManageTabSwitch';
import { getBaseUrl } from '@/services/urlconst';
import moment from 'moment';

const baseUrl = getBaseUrl();

/** 盘点计划管理页 service */
const InventoryPlanManageServices = (curRes: Record<string, any>) => {
  /**获取权限参数 */
  const queryTypeObj: Record<string, any> = AssetacquisitionTabSwitch(curRes);

  /***获取数据字典**/
  const { loadMapInfo, mapLoading } = getLoadMapList([
    `${getTenantID()}${ILoadMapTypeAll.ASSET_INNENTORY_STATUS}`, //资产类型
  ]);
  const assetType = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_INNENTORY_STATUS}`], 'name', 'id', true);

  /** 获取搜索参数 */
  const searchListParams = ManageSearchColumns(assetType);

  /***保存当前的搜索参数**/
  const [manageTableParams, setManageTableParams] = useState<Record<string, any>>({});

  /***管理页获取数据方法**/
  const { tableProps, data, loading, run } = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      let PostParams = {
        ...queryTypeObj,
        current: 1,
        pageSize: 10,
        sort: 'id',
        order: 'desc',
        queryType: 0,
        currentUserID: getUserID(),
        ...reqParams,
      };

      /***保存一份参数**/
      setManageTableParams(PostParams);

      const reqUrl = `${getBaseUrl()}/assetInventory/dataGrid/${queryTypeObj?.params}`;

      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, PostParams);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
    },
  );

  /***重新请求的方法**/
  const reloadRequest = useCallback((reqParams: AssetacquisitionManageAPI.IAssetTableRequestType | any) => {
    /**处理创建时间*/
    if (reqParams?.createTime) {
      const [timeStart, timeEnd] = reqParams.createTime;
      reqParams['createTimeStart'] = timeStart.format('YYYY-MM-DD 00:00:00');
      reqParams['createTimeEnd'] = timeEnd.format('YYYY-MM-DD 23:59:59');
      delete reqParams['createTime'];
    }

    /**处理签发时间*/
    if (reqParams?.signTime) {
      const [timeStart, timeEnd] = reqParams.signTime;
      reqParams['signTimeStart'] = timeStart.format('YYYY-MM-DD 00:00:00');
      reqParams['signTimeEnd'] = timeEnd.format('YYYY-MM-DD 23:59:59');
      delete reqParams['signTime'];
    }

    /**处理修改时间*/
    if (reqParams?.modifyTime) {
      const [timeStart, timeEnd] = reqParams.modifyTime;
      reqParams['modifyTimeStart'] = timeStart.format('YYYY-MM-DD 00:00:00');
      reqParams['modifyTimeEnd'] = timeEnd.format('YYYY-MM-DD 23:59:59');
      delete reqParams['modifyTime'];
    }

    /**处理作废时间*/
    if (reqParams?.cancelTime) {
      const [timeStart, timeEnd] = reqParams.cancelTime;
      reqParams['cancelTimeStart'] = timeStart.format('YYYY-MM-DD 00:00:00');
      reqParams['cancelTimeEnd'] = timeEnd.format('YYYY-MM-DD 23:59:59');
      delete reqParams['cancelTime'];
    }

    delete reqParams['createFormNameDept'];
    delete reqParams['createFormNameUser'];
    if (reqParams?.createrID && reqParams?.createrID?.length > 0) {
      reqParams['createrID'] = reqParams?.createrID?.toString();
    } else {
      delete reqParams['createrID'];
    }

    delete reqParams['cancelFormNameDept'];
    delete reqParams['cancelFormNameUser'];
    if (reqParams?.cancelerID && reqParams?.cancelerID?.length > 0) {
      reqParams['cancelerID'] = reqParams?.cancelerID?.toString();
    } else {
      delete reqParams['cancelerID'];
    }

    run({ ...reqParams });
  }, []);

  /***页面数据及分页信息**/
  const tableValues = useMemo(() => {
    return {
      data,
      pagination: tableProps?.pagination,
    };
  }, [data, tableProps]);

  /***搜索功能配置columns**/
  const searchList = useMemo(() => {
    return {
      searchList: searchListParams,
    };
  }, [searchListParams]);

  return {
    loading,
    reloadRequest,
    manageTableParams,
    ...tableValues, //页面列表值
    ...searchList,
  };
};

// 保存接口
const addServices = (curRes: Record<string, any>, Callback: (res: Record<string, any>) => void) => {
  const authority: any = AssetacquisitionTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      let PostParams = {
        params: authority.params,
        createrID: authority.createrID,
        createDepartmentID: authority.createDepartmentID,
        inventoryState: `${getTenantID()}${ILoadMapTypeAll.ASSET_INNENTORY_STATUS}1000`,
        state: `${getTenantID()}${ILoadMapTypeAll.ASSET_INPLAY_STATUS}1000`,
        businessType: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1016`,
        ...reqParams,
      };
      /**处理一下省市县*/
      PostParams = disposeArea(PostParams);
      const reqbody: Record<string, any> = disposeArea(PostParams);
      let reqUrl;
      // 物料管理
      reqUrl = `${getBaseUrl()}/assetInventory/add`;
      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, reqbody);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
      onSuccess: Callback,
    },
  );

  return {
    addPushRun: request.run,
    addPushLoading: request.loading,
    addPushPagination: request.pagination,
  };
};

// 盘点明细
const dataGridServices = (curRes: Record<string, any>) => {
  const authority: any = inventoryerSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      let PostParams = {
        params: authority.params,
        current: 1,
        pageSize: 10,
        ...reqParams,
      };
      /**处理一下省市县*/
      PostParams = disposeArea(PostParams);
      const reqbody: Record<string, any> = disposeArea(PostParams);
      let reqUrl;
      // 物料管理
      reqUrl = `${getBaseUrl()}/assetInventory/dataGridDetail/${authority.params}`;
      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, reqbody);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
    },
  );

  return {
    DataGridRun: request.run,
    taskPushLoading: request.loading,
    taskPushPagination: request.pagination,
    DataGriddata: request.data,
  };
};

// 盘点详情
const DetailServices = (curRes: Record<string, any>, Callback: (res: Record<string, any>) => void) => {
  const authority: any = AssetacquisitionTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      const obj = {
        ...reqParams,
        currentUserID: getUserID(),
      };
      // 物料管理
      let reqUrl = `${getBaseUrl()}/assetInventory/details`;
      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, obj);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
      onSuccess: Callback,
    },
  );

  return {
    DetailPushRun: request.run,
    DetailPushLoading: request.loading,
    DetailPushPagination: request.pagination,
    Detaildata: request.data,
    getDetailReload: request?.refresh,
  };
};

// 盘点编辑
const EditServices = (curRes: Record<string, any>, Callback: (res: Record<string, any>) => void) => {
  const authority: any = AssetacquisitionTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      let PostParams = {
        params: authority.params,
        createrID: authority.createrID,
        createDepartmentID: authority.createDepartmentID,
        ...reqParams,
      };
      /**处理一下省市县*/
      PostParams = disposeArea(PostParams);
      const reqbody: Record<string, any> = disposeArea(PostParams);
      let reqUrl;
      // 物料管理
      reqUrl = `${getBaseUrl()}/assetInventory/edit`;
      /***发起请求数据接口**/
      return requestFunComponFiex('PUT', reqUrl, reqbody);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
      onSuccess: Callback,
    },
  );

  return {
    EditPushRun: request.run,
    EditPushLoading: request.loading,
    EditPushPagination: request.pagination,
  };
};

// 撤销盘点
const RevokeServices = (curRes: Record<string, any>) => {
  const authority: any = AssetacquisitionTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      let PostParams = {
        params: authority.params,
        createrID: authority.createrID,
        createDepartmentID: authority.createDepartmentID,
        inventoryState: `${getTenantID()}${ILoadMapTypeAll.ASSET_INNENTORY_STATUS}1000`,
        state: `${getTenantID()}${ILoadMapTypeAll.ASSET_INPLAY_STATUS}1000`,
        ...reqParams,
      };
      const reqbody: Record<string, any> = disposeArea(PostParams);
      let reqUrl;
      // 物料管理
      reqUrl = `${getBaseUrl()}/assetInventory/revoke`;
      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, reqbody);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
    },
  );

  return {
    RevokeRun: request.run,
    taskPushLoading: request.loading,
    taskPushPagination: request.pagination,
  };
};

// 结束盘点
const completeServices = (curRes: Record<string, any>, callback) => {
  const authority: any = AssetacquisitionTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      let PostParams = {
        params: authority.params,
        createrID: authority.createrID,
        createDepartmentID: authority.createDepartmentID,
        inventoryState: `${getTenantID()}${ILoadMapTypeAll.ASSET_INNENTORY_STATUS}1005`,
        ...reqParams,
      };
      const reqbody: Record<string, any> = disposeArea(PostParams);
      let reqUrl;
      // 物料管理
      reqUrl = `${getBaseUrl()}/assetInventory/terminate/${reqParams.id}`;
      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, reqbody);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
      onSuccess: callback,
    },
  );

  return {
    completeRun: request.run,
    taskPushLoading: request.loading,
    taskPushPagination: request.pagination,
  };
};

// 导出盘点
const ExportServices = (callback: (res: any) => void, curRes: Record<string, any>) => {
  const queryTypeObj: any = DtailedTabSwitch(curRes);
  const authority: any = AssetacquisitionTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      let PostParams = {
        // params: authority.params,
        // createrID: authority.createrID,
        // createDepartmentID: authority.createDepartmentID,
        // ...reqParams,
        ...queryTypeObj,
        inventoryID: reqParams.id,
      };
      const reqbody: Record<string, any> = disposeArea(PostParams);
      let reqUrl;
      // 物料管理
      reqUrl = `${getBaseUrl()}/assetInventory/export/${queryTypeObj?.params}`;
      /***发起请求数据接口**/
      return requestFunHtml('POST', reqUrl, reqbody);
    },
    {
      manual: true,
      paginated: true,
      onSuccess: callback,
    },
  );

  return {
    ExportRun: request.run,
    taskPushLoading: request.loading,
    taskPushPagination: request.pagination,
  };
};

/**
 * 获取材料转资产详情
 * @param getDetailCallback
 * @returns
 */
const getDetailService = (getDetailCallback: (res: any) => void) => {
  const getDetail = useRequest(
    (id: any) => {
      let personUrl = `${getBaseUrl()}/assetApplyStuffasset/detail/${id}/ASSET_APPLY_STUFFASSET/${getUserID()}`;

      return requestFunComponFiex('GET', personUrl, {});
    },
    {
      manual: true,
      onSuccess: (res) => {
        getDetailCallback(res);
      },
    },
  );
  return {
    getDetailRun: getDetail?.run,
    getDetailLoading: getDetail?.loading,
  };
};

// 盘点明细
const DetailedServices = (curRes: Record<string, any>) => {
  const authority: any = DtailedTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      const obj = {
        ...authority,
        ...reqParams,
      };
      // 物料管理
      let reqUrl = `${getBaseUrl()}/assetInventory/dataGridDetail/${authority.params}`;
      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, obj);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
    },
  );

  const reloadRequest = useCallback((reqParams: AssetacquisitionManageAPI.IAssetTableRequestType | any) => {
    request.run({ ...reqParams });
  }, []);

  return {
    DetailPushRun: request.run,
    taskPushLoading: request.loading,
    taskPushPagination: request.pagination,
    Detaildata: request.data,
    getDetailReload: request?.refresh,
    reloadRequest,
  };
};

// 盘点差异详情
const differServices = (curRes: Record<string, any>, callback: (res: any) => void) => {
  const authority: any = DifferTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      const obj = {
        ...authority,
        ...reqParams,
      };
      let reqUrl = `${getBaseUrl()}/assetInventoryDifference/details`;
      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, obj);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
      onSuccess: callback,
    },
  );

  const reloadRequest = useCallback((reqParams: AssetacquisitionManageAPI.IAssetTableRequestType | any) => {
    request.run({ ...reqParams });
  }, []);

  return {
    DifferRun: request.run,
    DifferLoading: request.loading,
    DifferhPagination: request.pagination,
    Differdata: request.data,
    getDifferReload: request?.refresh,
    reloadRequest,
  };
};

// 盘点差异保存
const saveDifference = (curRes: Record<string, any>, callback: (res: any) => void) => {
  // const authority: any = DifferTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      // const obj = {
      //   ...authority,
      //   ...reqParams,
      // };
      let reqUrl = `${getBaseUrl()}/assetInventoryDifference/saveDifference`;
      /***发起请求数据接口**/
      return requestFunComponFiex('POST', reqUrl, reqParams);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
      onSuccess: callback,
    },
  );

  const reloadRequest = useCallback((reqParams: AssetacquisitionManageAPI.IAssetTableRequestType | any) => {
    request.run({ ...reqParams });
  }, []);

  return {
    SaveDifRun: request.run,
    SaveDifLoading: request.loading,
    SaveDifPagination: request.pagination,
    SaveDifdata: request.data,
    getSaveDifReload: request?.refresh,
    reloadRequest,
  };
};

// 岗位列表
const positionList = () => {
  // const authority: any = DifferTabSwitch(curRes);
  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      // const obj = {
      //   ...authority,
      //   ...reqParams,
      // };
      let reqUrl = `${getBaseUrl()}/positionController/treeGrid/${reqParams.id}`;
      /***发起请求数据接口**/
      return requestFunComponFiex('GET', reqUrl, reqParams);
    },
    {
      manual: true,
      paginated: true,
      defaultPageSize: 10,
      // onSuccess: callback,
    },
  );

  // const reloadRequest = useCallback((reqParams: AssetacquisitionManageAPI.IAssetTableRequestType | any) => {
  //   request.run({ ...reqParams });
  // }, []);

  return {
    positiondata: request.data,
    positionRun: request.run,
  };
};

// 导出明细
const ExportdetServices = (callback: (res: any) => void, curRes: Record<string, any>) => {
  const queryTypeObj: any = DtailedTabSwitch(curRes);

  const request = useRequest(
    (reqParams: AssetacquisitionManageAPI.IAssetTableRequestType) => {
      let PostParams = {
        ...queryTypeObj,
        ...reqParams,
      };

      let reqUrl = `${getBaseUrl()}/assetInventory/exportDetails/${queryTypeObj?.params}`;

      /***发起请求数据接口**/
      return requestFunHtml('POST', reqUrl, PostParams);
    },
    {
      manual: true,
      paginated: true,
      onSuccess: callback,
    },
  );

  return {
    ExportRun: request.run,
    ExportPushLoading: request.loading,
    ExportPushPagination: request.pagination,
  };
};

/** 领用审批通过后调用 */
const approvedInventorySerivice = (Callback: (res) => void) => {
  const request = useRequest(
    (payload: any) => {
      let params = {
        ...payload,
        createrID: getUserID(),
        createPositionID: getPosIDs(),
        createDepartmentID: getUserDepID(),
        createCompanyID: getCompanyID(),
      };

      let reqUrl = `${baseUrl}/assetInventory/approved`;

      return requestFunComponFiex('POST', reqUrl, params);
    },
    {
      manual: true,
      onSuccess: Callback,
    },
  );
  return {
    approvedInventoryRun: request?.run,
    approvedInventoryLoading: request?.loading,
  };
};

/**
 * 删除申请
 * @param callback 接口回调
 * @returns
 */
const deleteApplyManageService = (callback: (res: any, clickType: boolean) => void) => {
  const deleteApplyManage = useRequest(
    (params: any) => {
      let personUrl = `${baseUrl}/assetInventory/cancel`;
      let bodyParams = {
        ...params,
        cancelerID: getUserID(),
        cancelPositionID: getPosIDs(),
        cancelDepartmentID: getUserDepID(),
        cancelCompanyID: getCompanyID(),
      };
      return requestFunComponFiex('POST', personUrl, bodyParams);
    },
    {
      manual: true,
      onSuccess: (res: any) => {
        callback(res, false);
      },
    },
  );
  return {
    deleteApplyManageRun: deleteApplyManage?.run,
    deleteApplyManageLoading: deleteApplyManage?.loading,
  };
};

export {
  deleteApplyManageService,
  InventoryPlanManageServices,
  addServices,
  dataGridServices,
  DetailServices,
  EditServices,
  RevokeServices,
  ExportServices,
  completeServices,
  getDetailService,
  DetailedServices,
  differServices,
  saveDifference,
  positionList,
  ExportdetServices,
  approvedInventorySerivice,
};
